﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Affinity.Core.Collections;
using Affinity.Flux;

namespace Service
{
    public class AlarmManager
    {
        [Inlet(Contracts.Time.AddAlarm)]
        public void AddAlarm(DateTime alarmTime)
        {
            alarmTime = new DateTime(alarmTime.Year, alarmTime.Month, alarmTime.Day, alarmTime.Hour, alarmTime.Minute, alarmTime.Second);
            _alarms.Add(alarmTime);
            RaiseAlarmAdded(alarmTime);
        }

        [Inlet(Contracts.Time.CurrentTime)]
        public DateTime CurrentTime
        {
            get { return _currentTime; }
            set
            {
                if (value == _currentTime) return;
                _currentTime = value;
                _currentTime = new DateTime(_currentTime.Year, _currentTime.Month, _currentTime.Day, _currentTime.Hour, _currentTime.Minute, _currentTime.Second);
                if (_alarms.Any(alarm => alarm == _currentTime)) RaiseAlarmFired();
            }
        }
        private DateTime _currentTime;

        [Outlet(Contracts.Time.AlarmAdded)]
        public event Action<DateTime> AlarmAdded;

        private void RaiseAlarmAdded(DateTime alarmTime)
        {
            var alarmAdded = AlarmAdded;
            if (alarmAdded != null) alarmAdded(alarmTime);
        }

        [Outlet(Contracts.Time.AlarmFired)]
        public event Action<string> AlarmFired;

        private void RaiseAlarmFired()
        {
            var alarmFired = AlarmFired;
            if (alarmFired != null) alarmFired("Alarm!");
        }

        private readonly SynchronizedList<DateTime> _alarms = new SynchronizedList<DateTime>(); 
    }
}
